package lab03.Test06;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.*;

public class Test {
    public static void main(String[] args) {
        String path="D://world.txt";
        RandomAccessFile randomAccessFile=null;
        int count=0;
        Map<String,Integer> map=new HashMap<String, Integer>();
        try {
           randomAccessFile=new RandomAccessFile(path,"rw");
            String line=null;
            while ((line=randomAccessFile.readLine())!=null) {
                count++;
                // line.length();
                //先要判断map中有没有这个key，没有就直接value赋值1


                    if (map.get(line) == null) {
                        map.put(line, 1);

                    } else {
                        map.put(line, map.get(line) + 1);
                    }
                }
            System.out.println("总的单词数："+count);
            System.out.println("不同的单词数："+map.size());

            /*
            * 因为MAP集合不能排序，所以只能将MAP集合转化成list集合
            */
           // Set<Map.Entry<String,Integer>>entrySet=
//            ArrayList<Map.Entry<String,Integer>>list=new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
//            Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
//                @Override
//                public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
//                    return 0;
//                }
//            });
//            for (int i=0;i<list.size();i++){
//                Map.Entry<String,Integer>entry=list.get(i);
//                map.put(entry.getKey(),entry.getValue());
//                System.out.println(entry.getKey() + ":" + entry.getValue());
//            }
            List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());


            Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
                @Override
                public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                    return o2.getValue().compareTo(o1.getValue());
                }
            });
            for (Map.Entry<String, Integer> entry : list) {
                System.out.println(entry.getKey() + ":" + entry.getValue());
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                randomAccessFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
